package ru.efimmatytsin.tweeterella;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import ru.efimmatytsin.tweeterella.entities.Photo;
import ru.efimmatytsin.tweeterella.entities.User;
import ru.efimmatytsin.tweeterella.holders.UserInformationModelHolder;
import ru.efimmatytsin.tweeterella.services.PhotoService;
import ru.efimmatytsin.tweeterella.services.UserService;
import ru.efimmatytsin.tweeterella.validators.RegistrationFormValidator;
import ru.efimmatytsin.tweeterella.viewmodels.RegistrationFormViewModel;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.Date;
import java.util.Calendar;

/**
 * Created by Efim Matytsin on 18.02.15.
 */
@Controller
@RequestMapping("/registration")
public class RegistrationController {

    @Autowired
    private UserService userService;

    @Autowired
    private PhotoService photoService;

    @Autowired
    private RegistrationFormValidator validator;

    @Autowired
    private UserInformationModelHolder userInformationModelHolder;

    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
            throws ServletException {
        // Convert multipart object to byte[]
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());

    }

    @RequestMapping(method = RequestMethod.GET)
    public String initializeView(Model model) {
        //model.addAttribute("message", "Hello world!");
        model.addAttribute("userData",new RegistrationFormViewModel());
        return "registration";
    }

    @RequestMapping(value="/new", method=RequestMethod.POST)
    @Transactional
    public String submitForm(@ModelAttribute("userData") RegistrationFormViewModel registrationFormViewModel,
                             BindingResult bindingResult,
                             ModelMap model,HttpServletRequest request){

        validator.validate(registrationFormViewModel,bindingResult);
        if(bindingResult.hasErrors()){
            return "registration";
        }

        MultipartFile file = registrationFormViewModel.getFile();
        String saveDirectory = request.getSession().getServletContext().getRealPath("/")+"uploadImages\\";
        Photo photo = Photo.createPhoto().setCreated(new Date(Calendar.getInstance().getTimeInMillis()))
                .setSubject("Update photo profile");



        try {

            String fileName = file.getOriginalFilename();
            File destination = new File(saveDirectory + fileName);
            file.transferTo(destination);
            photo.setUrl("uploadImages\\" + fileName);
        } catch (Exception e) {
            //return "You failed to upload " + fileName + " => " + e.getMessage();
        }

        User user = User.createUser();

        user.setEmail(registrationFormViewModel.getEmail());
        user.setFirstName(registrationFormViewModel.getFirstName());
        user.setLastName(registrationFormViewModel.getLastName());
        user.setPassword(registrationFormViewModel.getPassword());
        user.setUsername(registrationFormViewModel.getUsername());
        user.setPhoto(photo);




        photo.setOwner(user);

        photoService.savePhoto(photo);
        userService.saveUser(user);
        userInformationModelHolder.setUser(user);
        return "redirect:/profile";
    }
}
